package com.shuqi.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.text.TextUtils;

import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.MyUrlTools;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.database.model.UserInfo;
import com.shuqi.model.SyncBookMarksModel;
import com.shuqi.model.bean.SyncBookMarkInfo;
import com.shuqi.model.bean.SyncBookMarkUpLoadInfo;
import com.shuqi.model.bean.SyncBookMarksData;
import com.shuqi.model.manager.BookMarkManager;
import com.shuqi.model.manager.MyAccountManager;

public class SyncBookMarks {
    /** 书旗平台类型：书旗 */
    private static final String TYPE_SOURCE_SHUQI = "1";
    /** 书旗平台类型：神马 */
    private static final String TYPE_SOURCE_SHENMA = "2";

    /** param2 字段特殊含义： 神马书签类型：app神马书签 */
    private static final String TYPE_PARAM2_SHENMA_APP = "0";
    /** param2 字段特殊含义： 神马书签类型：app网页web书签 */
    private static final String TYPE_PARAM2_SHENMA_WEB = "1";

    /** sourceId 字段特殊含义： 书旗书签类型：app8.0新书签 */
    private static final String TYPE_SOURCEID_SHUQI_PAY = "-1";
    /** sourceId 字段特殊含义： 书旗书签类型：app8.0之前版本的书签 */
    private static final String TYPE_SOURCEID_SHUQI_OLD = "-2";

    private static final String logTag = "SyncBookMarks";

    /** 正在云同步书签 */
    private static boolean isSyncingBookMark = false;

    /**
     * 云同步书签
     * 
     * @param applicationContext
     * @param userInfo
     * @param uilinstener
     * @param sendData 需要下发数据时传 yes(必须传yes,不能传null或"");不需要下发数据时传入no
     */
    public static synchronized void syncBookMarks(final Context applicationContext,
            final UserInfo userInfo, final SyncBookMarksResultToUILinstener uilinstener,
            final String sendData) {
        Log4an.e(logTag, "isSyncingBookMark="+isSyncingBookMark+",userInfo="+userInfo.getUserId());
        if (isSyncingBookMark || MyAccountManager.isGuestUser(userInfo)) {
            Log4an.e(logTag, "return,"
                    + (isSyncingBookMark ? "is Syncing BookMark "
                            : "this user syncBookMark permission denied"));
            if (uilinstener != null) {
                uilinstener.onResult(false, null);
            }
            return;
        }
        isSyncingBookMark = true;
        Log4an.e(logTag, "开始云同步书签：" + isSyncingBookMark + ",userId=" + userInfo.getUserId()
                + ",sendData=" + sendData);
        // 获取书签列表
        List<BookMarkInfo> marks =
                BookMarkInfoDao.getInstance().getSynBookMarkList(userInfo.getUserId(), -1);
        // 取出书签列表时的时间
        final long readTime = System.currentTimeMillis();

        Log4an.e(logTag, "userId:" + userInfo.getUserId() + ",marks:"
                + (marks == null ? "null" : marks.size()));
        SyncResultLinstener resultLinstener = new SyncResultLinstener() {
            @Override
            public void onResult(boolean isSuccess, SyncBookMarksData markdate) {
                if (!"no".equals(sendData)) {

                    if (markdate != null) {
//                        Log4an.e(logTag, "on SyncResult: markdate code:" + markdate.getCode()
//                                + ", message:" + markdate.getMessage());
                    }
                    if (isSuccess && markdate != null
                            && SyncBookMarksData.CODE_SUCCESS.equals(markdate.getCode())
                            && markdate.getList() != null) {
                        Log4an.e(logTag, "on SyncResult: list.Size=" + markdate.getList().size());
                        List<SyncBookMarkInfo> list = markdate.getList();
                        List<BookMarkInfo> markList =
                                syncInfosToBookMarkInfos(list, userInfo.getUserId());
                        // 获取云同步之前到目前之间的有新操作的书签
                        List<BookMarkInfo> localNewList =
                                BookMarkInfoDao.getInstance().getSynBookMarkList(
                                        userInfo.getUserId(), readTime);
                        // 合并云端和本地新产生的书签
                        Map<String, BookMarkInfo> map =
                                BookMarkManager.getInstance().mergeBookMarkList(markList,
                                        localNewList);
                        // 保存最终的书签
                        BookMarkInfoDao.getInstance().updateSaveSynBookMark(userInfo.getUserId(),
                                map);
                        // BookMarkInfoDao.getInstance().saveSynBookMarkList(userInfo.getUserId(),
                        // map);
                        Log4an.e(logTag, "网络上最新的：onLineList:"
                                + (markList == null ? "null" : markList.size()));
                        Log4an.e(logTag, "本地最新的：localNewList:"
                                + (localNewList == null ? "null" : localNewList.size()));
                        Log4an.e(logTag, "合并后的：map:" + (map == null ? "null" : map.size()));

                        if (uilinstener != null) {
                            uilinstener.onResult(true, markList);
                        }
                        isSyncingBookMark = false;
                    } else {
                        if (uilinstener != null) {
                            uilinstener.onResult(false, null);
                        }
                        isSyncingBookMark = false;
                    }
                }
                isSyncingBookMark = false;
            }
        };
        SyncBookMarksModel model = new SyncBookMarksModel(applicationContext, resultLinstener);
        model.loadData(userInfo.getUserId(), sendData, getBookMarkListXML(marks));
    }

    /***
     * 把云同步下来的数据，分类整理成书签类型的数据
     * 
     * @param syncList
     * @param userId
     * @return
     */
    private static List<BookMarkInfo> syncInfosToBookMarkInfos(List<SyncBookMarkInfo> syncList,
            String userId) {
        List<BookMarkInfo> markList = new ArrayList<BookMarkInfo>();
        int size = syncList.size();
        for (int i = 0; i < size; i++) {
            SyncBookMarkInfo info = syncList.get(i);
//            Log4an.i(logTag, info.toString());

            BookMarkInfo mark = new BookMarkInfo();
            markList.add(mark);

            mark.setUserId(userId);
            mark.setBookId(info.getBookId());
            mark.setChapterId(info.getChapterId());
            mark.setBookName(info.getBookName());
            mark.setChapterName(info.getChapterName());
            mark.setBookCoverImgUrl(info.getImgUrl());
            mark.setDeleteFlag(BookMarkInfo.FLAG_RETAIN);

            if (!TextUtils.isEmpty(info.getUpdateTime())) {
                try {
                    mark.setUpdateTime(Long.parseLong(info.getUpdateTime()));
                } catch (Exception e) {
                    e.printStackTrace();
                    mark.setUpdateTime(System.currentTimeMillis());
                }
            } else {
                mark.setUpdateTime(System.currentTimeMillis());
            }

            int number = 0;
            if (!TextUtils.isEmpty(info.getNumChapter())) {
                try {
                    number = Integer.valueOf(info.getNumChapter());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mark.setTotalChapter(number);
            if (!TextUtils.isEmpty(info.getPercent())) {
                try {
                    mark.setPercent(Float.valueOf(info.getPercent()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (TYPE_SOURCE_SHUQI.equals(info.getPlatform())) {
                if (TYPE_SOURCEID_SHUQI_PAY.equals(info.getSourceId())) { // 书旗收费书签
                    mark.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
                    try {
                        mark.setBookReadByte(Integer.valueOf(info.getParam1()));
                    } catch (Exception e) {
                        mark.setBookReadByte(0);
                        e.printStackTrace();
                    }
                } else if (TYPE_SOURCEID_SHUQI_OLD.equals(info.getSourceId())) {// 书旗老书签
                    mark.setBookType(BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK);
                    try {
                        mark.setBookReadByte(Integer.valueOf(info.getParam1()));
                    } catch (Exception e) {
                        mark.setBookReadByte(0);
                        e.printStackTrace();
                    }
                } else {
                    Log4an.e(
                            logTag,
                            "old bookMark:" + info.getPlatform() + ", sourceId:"
                                    + info.getSourceId());
                    mark.setBookType(BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK);
                    try {
                        mark.setBookReadByte(Integer.valueOf(info.getParam1()));
                    } catch (Exception e) {
                        mark.setBookReadByte(0);
                        e.printStackTrace();
                    }
                    mark.setSourceId(info.getSourceId());
                }
            } else if (TYPE_SOURCE_SHENMA.equals(info.getPlatform())) { // 神马书签
                if (TYPE_PARAM2_SHENMA_APP.equals(info.getParam2())) {
                    mark.setBookType(BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK);
                    mark.setSourceId(info.getSourceId());
                    try {
                        mark.setBookReadByte(Integer.valueOf(info.getParam1()));
                    } catch (Exception e) {
                        mark.setBookReadByte(0);
                        e.printStackTrace();
                    }
                } else if (TYPE_PARAM2_SHENMA_WEB.equals(info.getParam2())) {
                    mark.setBookType(BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK);
                    mark.setSourceId(info.getSourceId());
                } else {
                    Log4an.e(
                            logTag,
                            "error source:" + info.getPlatform() + ", Platform:"
                                    + info.getPlatform());
                    mark.setBookType(BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK);
                    mark.setSourceId(info.getSourceId());
                    try {
                        mark.setBookTotalByte(Integer.valueOf(info.getParam2()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return markList;
    }

    /***
     * 把书签数据组织成XML格式，上传服务器
     * 
     * @param marks
     * @return
     */
    private static String getBookMarkListXML(List<BookMarkInfo> marks) {
        StringBuilder sb = new StringBuilder();
        sb.append("<Bookmarks>");
        // 组织书签数据
        if (marks != null) {
            int size = marks.size();
            for (int i = 0; i < size; i++) {
//                Log4an.i(logTag, "mark:" + marks.get(i).toString());

                BookMarkInfo mark = marks.get(i);
                SyncBookMarkUpLoadInfo upInfo = new SyncBookMarkUpLoadInfo();

                upInfo.setBookId(mark.getBookId());
                upInfo.setChapterId(mark.getChapterId());
                upInfo.setFlag(mark.getDeleteFlag());

                upInfo.setNumChapter(String.valueOf(mark.getTotalChapter()));
                upInfo.setPercent(String.valueOf(mark.getPercent()));
                upInfo.setUpdateTime(String.valueOf(mark.getUpdateTime() < 1 ? System
                        .currentTimeMillis() : mark.getUpdateTime()));
                // 书旗收费书签
                if (BookMarkInfo.TYPE_NEW_PAY_BOOKMARK == mark.getBookType()) {
                    upInfo.setSource(TYPE_SOURCE_SHUQI); // 书签平台
                    upInfo.setParam1(String.valueOf(mark.getBookReadByte())); // 阅读参数
                    upInfo.setSourceId(TYPE_SOURCEID_SHUQI_PAY);
                    // 书旗老书签
                } else if (BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK == mark.getBookType()) {
                    upInfo.setSource(TYPE_SOURCE_SHUQI); // 书签平台
                    upInfo.setParam1(String.valueOf(mark.getBookReadByte())); // 阅读参数
                    upInfo.setSourceId(TYPE_SOURCEID_SHUQI_OLD);

                    // 神马app书签
                } else if (BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK == mark.getBookType()) {
                    upInfo.setSource(TYPE_SOURCE_SHENMA); // 书签平台
                    upInfo.setSourceId(mark.getSourceId()); // 来源id
                    upInfo.setParam1(String.valueOf(mark.getBookReadByte())); // 阅读参数
                    upInfo.setParam2(TYPE_PARAM2_SHENMA_APP);// 神马书签区分app和web书签

                    // 神马老网页书签
                } else if (BookMarkInfo.TYPE_OLD_WEB_BOOKMARK == mark.getBookType()) {
                    upInfo.setSource(TYPE_SOURCE_SHENMA); // 书签平台
                    upInfo.setSourceId(mark.getSourceId()); // 来源id
                    upInfo.setChapterId(MyUrlTools.getChapterIdFromWebBookMarkUrl(mark
                            .getFilePath()));
                    upInfo.setParam2(TYPE_PARAM2_SHENMA_WEB);// 神马书签区分app和web书签
                    // 神马网页
                } else if (BookMarkInfo.TYPE_NEW_SHENMA_WEB_BOOKMARK == mark.getBookType()) {
                    upInfo.setSource(TYPE_SOURCE_SHENMA); // 书签平台
                    upInfo.setSourceId(mark.getSourceId()); // 来源id
                    upInfo.setParam2(TYPE_PARAM2_SHENMA_WEB);// 神马书签区分app和web书签
                    upInfo.setChapterId(mark.getChapterId());
                }
                sb.append("<Bookmark ");

                sb.append(" flag=\"" + upInfo.getFlag() + "\"");
                sb.append(" source=\"" + upInfo.getSource() + "\"");
                sb.append(" bookId=\"" + upInfo.getBookId() + "\"");
                sb.append(" chapterId=\"" + upInfo.getChapterId() + "\"");
                sb.append(" sourceId=\"" + upInfo.getSourceId() + "\"");
                sb.append(" param1=\"" + upInfo.getParam1() + "\"");
                sb.append(" param2=\"" + upInfo.getParam2() + "\"");
                sb.append(" percent=\"" + upInfo.getPercent() + "\"");
                sb.append(" numchapter=\"" + upInfo.getNumChapter() + "\"");
                sb.append(" updateTime=\"" + upInfo.getUpdateTime() + "\"");

                sb.append("/>");
            }
        }
        sb.append("</Bookmarks>");
        return sb.toString();

    }

    /**
     * 云同步书签联网完成后，数据层的回调监听
     */
    public interface SyncResultLinstener {
        public void onResult(boolean isSuccess, SyncBookMarksData markdate/* ,boolean isDeal */);
    }
    /**
     * 云同步书签完成后，回调UI层的监听
     */
    public interface SyncBookMarksResultToUILinstener {
        public void onResult(boolean isSuccess, List<BookMarkInfo> markList);
    }

}
